from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

from ..core.database import get_db
from ..models import Department, User, UserRole
from ..api.auth import get_current_user
from ..schemas.department import DepartmentInfo, DepartmentCreate, DepartmentUpdate

router = APIRouter()

@router.get("/", response_model=List[DepartmentInfo])
async def list_departments(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取部门列表"""
    departments = db.query(Department).all()
    return [
        DepartmentInfo(
            id=dept.id,
            name=dept.name,
            description=dept.description,
            created_at=dept.created_at
        )
        for dept in departments
    ]

@router.post("/", response_model=DepartmentInfo)
async def create_department(
    dept_data: DepartmentCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建部门（仅管理员）"""
    if current_user.role != UserRole.ADMIN:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 检查部门名是否已存在
    if db.query(Department).filter(Department.name == dept_data.name).first():
        raise HTTPException(status_code=400, detail="部门名已存在")
    
    new_dept = Department(
        name=dept_data.name,
        description=dept_data.description
    )
    
    db.add(new_dept)
    db.commit()
    db.refresh(new_dept)
    
    return DepartmentInfo(
        id=new_dept.id,
        name=new_dept.name,
        description=new_dept.description,
        created_at=new_dept.created_at
    )

@router.put("/{dept_id}", response_model=DepartmentInfo)
async def update_department(
    dept_id: int,
    dept_data: DepartmentUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新部门信息（仅管理员）"""
    if current_user.role != UserRole.ADMIN:
        raise HTTPException(status_code=403, detail="权限不足")
    
    dept = db.query(Department).filter(Department.id == dept_id).first()
    if not dept:
        raise HTTPException(status_code=404, detail="部门不存在")
    
    if dept_data.name:
        dept.name = dept_data.name
    if dept_data.description is not None:
        dept.description = dept_data.description
    
    db.commit()
    db.refresh(dept)
    
    return DepartmentInfo(
        id=dept.id,
        name=dept.name,
        description=dept.description,
        created_at=dept.created_at
    )

@router.delete("/{dept_id}")
async def delete_department(
    dept_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除部门（仅管理员）"""
    if current_user.role != UserRole.ADMIN:
        raise HTTPException(status_code=403, detail="权限不足")
    
    dept = db.query(Department).filter(Department.id == dept_id).first()
    if not dept:
        raise HTTPException(status_code=404, detail="部门不存在")
    
    # 检查是否有用户属于该部门
    if db.query(User).filter(User.department_id == dept_id).first():
        raise HTTPException(status_code=400, detail="该部门下还有用户，无法删除")
    
    db.delete(dept)
    db.commit()
    
    return {"message": "部门删除成功"}